<script setup lang="ts">
import EChartsComponent from "@/components/EChartsComponent/index.vue";
import "plus-pro-components/es/components/search/style/css";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { computed, onMounted, reactive, ref } from "vue";
import { getDataBySQLDesc } from "@/api/common";
import { usePagination } from "@/hooks/usePagination";
import { log } from "node:console";
defineOptions({
  name: "EarlyDelivery"
});
const pagination = usePagination();
const searchColumns: PlusColumn[] = [
  {
    label: "年份",
    prop: "dhnd",

    valueType: "date-picker",
    fieldProps: {
      type: "year",
      valueFormat: "YYYY",
      placeholder: "请选择年份"
    }
  },
  {
    label: "到货开始时间",
    prop: "kssj",
    labelWidth: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "date",
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      placeholder: "请选择开始时间"
    }
  },
  {
    label: "到货结束时间",
    prop: "jssj", labelWidth: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "date",
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      placeholder: "请选择结束时间"
    }
  },
];
const option = computed(() => {
  return {
    tooltip: {
      trigger: "axis",
      position: function (point, params, dom, rect, size) {
        // point: 鼠标位置，格式为 [x, y]
        // params: 提示框所包含的数据信息
        // dom: 提示框的 DOM 元素
        // rect: 鼠标所在图形的包围盒，格式为 {x, y, width, height}
        // size: 提示框的大小，格式为 {contentSize: [width, height], outerSize: [width, height]}
        return [point[0] - 50, point[1] - 50]; // 设置提示框在鼠标上方 20px 处
      },
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      }
    },
    legend: {
      type: "scroll",
      data: ['应到批次', "全货到货批次", "全货入库批次", "全货到货率", "全货入库率"]
    },
    xAxis: [
      {
        type: "category",
        data: [

          "一月",
          "二月",
          "三月",
          "四月",
          "五月",
          "六月",
          "七月",
          "八月",
          "九月",
          "十月",
          "十一月",
          "十二月"
        ],
        axisPointer: {
          type: "shadow"
        }
      }
    ],
    yAxis: [
      {
        type: "value",
        axisLabel: {
          formatter: "{value}"
        }
      },
      {
        type: "value",
        axisLabel: {
          formatter: "{value}%"
        }
      }
    ],
    series: seriesData.value
  }
});
const seriesData = computed(() => {
  let arr = []
  let nameList = ['应到批次', '全货到货批次', '全货入库批次', '全货到货率', '全货入库率']
  nameList.map((item, index) => {
    let obj = {
      name: nameList[index],
      type: index > 2 ? "line" : 'bar',
      smooth: true,
      yAxisIndex: index > 2 ? 0 : 1,
      tooltip: {
        valueFormatter: function (value) {
          if (index > 2) {
            return value + "%";
          } else {
            return value;
          }

        }
      },
      data: []
    }
    apiData.value.map((item1) => {
      if (index > 2) {
        obj.data.push(item1[item] * 100)
      } else {
        obj.data.push(item1[item])
      }

    })
    arr.push(obj)
  })
  return arr
})
const columns = computed(() => [
  {
    label: "项目",
    prop: "project"
  },

  {
    label: form.value.dhnd + "年Q1",
    children: [
      { label: "一月", prop: "jan" },
      { label: "二月", prop: "feb" },
      { label: "三月", prop: "mar" }
    ]
  },
  {
    label: form.value.dhnd + "年Q2",
    children: [
      { label: "四月", prop: "apr" },
      { label: "五月", prop: "may" },
      { label: "六月", prop: "jun" }
    ]
  },
  {
    label: form.value.dhnd + "年Q3",
    children: [
      { label: "七月", prop: "jul" },
      { label: "八月", prop: "aug" },
      { label: "九月", prop: "sep" }
    ]
  },
  {
    label: form.value.dhnd + "年Q4",
    children: [
      { label: "十月", prop: "oct" },
      { label: "十一月", prop: "nov" },
      { label: "十二月", prop: "dec" }
    ]
  },

]);
// 新增响应式数据，用于存储从接口获取的数据
const columns2 = computed(() => [
  {
    label: "采购到厂日期",
    prop: "采购到厂日期"
  },
  {
    label: "全货到货批次",
    prop: "全货到货批次"
  },
  {
    label: "应到批次",
    prop: "应到批次"
  },
  {
    label: "全货到货率",
    prop: "全货到货率"
  },]
)
const columns3 = computed(() => [
  {
    label: "供应商",
    prop: "供应商"
  },
  {
    label: "应到批次",
    prop: "应到批次"
  },
  {
    label: "按时到货批次",
    prop: "按时到货批次"
  },

  {
    label: "提前到货批次",
    prop: "提前到货批次"
  },
  {
    label: "全货到货批次",
    prop: "全货到货批次"
  },
  {
    label: "全货到货率",
    prop: "全货到货率"
  },])
const columns4 = computed(() => [
  {
    label: "采购批次",
    prop: "采购批次"
  },
  {
    label: "要求到厂日期",
    prop: "要求到库日期"
  },

  {
    label: "批次采购数量",
    prop: "批次采购数量"
  }, {
    label: "批次到货数量",
    prop: "批次到货数量"
  },
  {
    label: "收货数量",
    prop: "收货数量"
  },
  {
    label: "入库数量",
    prop: "入库数量"
  },
  {
    label: "收货审核日期",
    prop: "收货审核日期"
  },
  {
    label: "执行状态",
    prop: "执行状态"
  },])
const apiData = ref([]);
const apiData1 = ref([]);
const apiData2 = ref([]);
const apiData3 = ref([]);
const apiData4 = ref([]);
// const apiData2Name = ref('');
const data = computed(() => {
  let arr = ['应到批次', '全货到货批次', '全货到货率', Number(form.value.dhnd) - 1 + "年全货率",]
  let result = [];
  arr.map(item => {
    result.push({
      project: item,
      jan: "",
      feb: "",
      mar: "",
      apr: "",
      may: "",
      jun: "",
      jul: "",
      aug: "",
      sep: "",
      oct: "",
      nov: "",
      dec: "",

    },)
  })
  let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
  let arr2 = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
  // 根据 apiData 更新 result
  apiData.value.map(item => {
    let index = arr1.indexOf(item.采购到库月份);
    if (index > -1) {
      result[0][arr2[index]] = item.应到批次;
      result[1][arr2[index]] = item.全货到货批次;
      result[2][arr2[index]] = item.全货到货率 * 100 + '%';
    }
  });
  apiData1.value.map(item => {
    let index = arr1.indexOf(item.采购到库月份);
    if (index > -1) {
      result[3][arr2[index]] = item.全货到货率 * 100 + '%';
    }
  });
  return result;
});

const form = ref({
  dhnd: "",
  kssj: "",
  jssj: "",
  gys: '',
  gysNmae: ''
});
// 获取年份
const getTime = async () => {
  const { data } = await getDataBySQLDesc({ action: "public/get_server_sysdate" });
  form.value.dhnd = data[0].年
  getData()
  getData1()
}
// 按年度统计每月到货批次 全货率
const getData = async () => {
  let params = {
    action: "biz/reports/get_tqdh_my_pctj",
    dhnd: form.value.dhnd,
  }
  const { data } = await getDataBySQLDesc(params);
  apiData.value = data;
}
// 上年度统计每月到货批次 全货率
const getData1 = async () => {
  let dhnd = Number(form.value.dhnd) - 1;
  let params = {
    action: "biz/reports/get_tqdh_my_pctj",
    dhnd: dhnd + '',
  }
  const { data } = await getDataBySQLDesc(params);
  apiData1.value = data;
}
// 按时间 到货批次 全货率明细表
const getData2 = async () => {
  let params = {
    action: "biz/reports/get_tqdh_zdsj_gys_pctj",
    kssj: form.value.kssj,
    jssj: form.value.jssj,
  }
  const { data } = await getDataBySQLDesc(params);
  apiData2.value = data
  apiData2.value.map(e => {
    e.全货到货率 = (e.全货到货率 * 100).toFixed(2) + "%"
  })
}
// 按指定时间段统计供应商到货批次 全货率 表格
const getData3 = async () => {
  let params = {
    action: "biz/reports/get_tqdh_zdsj_mr_pctj",
    kssj: form.value.kssj || '',
    jssj: form.value.jssj || '',
  }
  const { data } = await getDataBySQLDesc(params);
  apiData3.value = data
  apiData3.value.map(e => {
    e.全货到货率 = (e.全货到货率 * 100).toFixed(2) + "%"
  })
}
// 按指定时间段统计供应商到货批次 全货率 表格明细
const getData4 = async () => {
  let params = {
    action: "biz/reports/get_tqdh_zdsj_zdgys_pctjmx",
    kssj: form.value.kssj || '',
    jssj: form.value.jssj || '',
    gys: form.value.gys,
  }
  const { data } = await getDataBySQLDesc(params);
  apiData4.value = data
  apiData4.value.map(e => {
    e.全货到货率 = (e.全货到货率 * 100).toFixed(2) + "%"
  })
}
const handleCellClick = (row, column, cell, event) => {
  let arr = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
  let month = arr.indexOf(column.label) + 1
  form.value.kssj = form.value.dhnd + '-' + month + '-01 00:00:00';
  if (month === 4 || month === 6 || month === 9 || month === 11) {
    form.value.jssj = form.value.dhnd + '-' + month + '-30 00:00:00';
  } else if (month === 2) {
    const nowYear = form.value.dhnd;
    if ((nowYear % 4 === 0 && nowYear % 100 !== 0) || (nowYear % 400 === 0)) {
      form.value.jssj = form.value.dhnd + '-' + month + '-29 00:00:00';
    } else {
      form.value.jssj = form.value.dhnd + '-' + month + '-28 00:00:00';
    }
  } else {
    form.value.jssj = form.value.dhnd + '-' + month + '-31 00:00:00';
  }
  getData2()
}
const handleCellClick2 = (row, column, cell, event) => {
  form.value.gys = row.供应商编号
  form.value.gysNmae = row.供应商
  getData4()
}
const recoverFn2 = () => {
  form.value.gys = '';
  form.value.gysNmae = '';
  apiData4.value = [];
  getData3()
};
const recoverFn1 = () => {
  form.value.kssj = '';
  form.value.jssj = '';
  apiData2.value = [];
  getData()
  getData1()
};
const handleChange = () => { };
const handleSearch = () => {
  if (form.value.kssj || form.value.jssj) {
    getData2()
  } else {
    apiData2.value = []
    getData()
    getData1()
  }

  if (form.value.gys) {
    getData3()
  } else {
    getData4();
  }

};
const handleRest = () => {
  apiData2.value = []
  form.value.kssj = '';
  form.value.jssj = '';
  getTime();
};
onMounted(() => {
  getTime();
  getData3();
});
</script>

<template>
  <div class="page-content">
    <el-card>
      <PlusSearch v-model="form" searchText="搜索" resetText="重置" expand-text="展开" retractText="收起"
        :columns="searchColumns" :show-number="3" label-position="right" @change="handleChange" @search="handleSearch"
        @reset="handleRest" />
    </el-card>
    <el-card class="card">
      <div class="operate" v-if="!apiData2.length">
        <el-button type="primary">导出</el-button>
      </div>
      <div class="operate" v-else>
        <el-button type="primary" @click="recoverFn1">返回</el-button>
        <div class="text-center py-[10px] text-xl font-bold">全货明细表（{{ form.kssj }}至{{ form.jssj || '当前' }}） </div>
      </div>
      <PureTable v-if="!apiData2.length" ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip
        :data="data" :columns="columns" @cell-click="handleCellClick" />
      <PureTable v-else ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip :data="apiData2"
        :columns="columns2" @cell-click="handleCellClick" />
    </el-card>
    <el-card class="card">
      <div class="text-center py-[10px] text-xl font-bold">
        {{ form.dhnd }}年采购物料到货全货率
      </div>
      <div class="h-[400px]">
        <EChartsComponent :extraOptions="option" type="bar" />
      </div>
    </el-card>

    <el-card class="card">
      <!-- <div class="operate" v-if="!apiData4.length">
        <el-button type="primary">导出</el-button>
      </div> -->
      <div class="operate" v-if="apiData4.length">
        <el-button type="primary" @click="recoverFn2">返回</el-button>
        <div class="text-center py-[10px] text-xl font-bold">{{ form.gysNmae }} 全货明细表（{{ form.kssj }}至{{ form.jssj ||
          '当前' }}） </div>
      </div>
      <PureTable v-if="!apiData4.length" ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip
        :data="apiData3" :columns="columns3" @cell-click="handleCellClick2" />
      <PureTable v-else ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip :data="apiData4"
        :columns="columns4" />
    </el-card>
  </div>
</template>
<style lang="css" scoped>
.card {
  margin-top: 20px;
}

.operate {
  margin-bottom: 20px;
}
</style>
